﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sysgeprava.Entities;

namespace Sysgeprava.Repository
{
    public class UbigeoRepository:MasterRepository,IUbigeoRepository
    {
        public List<UBIGEO> GetAllFromUbigeo()
        {
            var query = from e in context.UBIGEOs
                        select e;
            return query.ToList();
        }

        public List<UBIGEO> GetAllFromUbigeoByCriterio(string criterio)
        {
            var query = from u in context.UBIGEOs
                        select u;
            if (criterio != null && criterio != string.Empty && criterio != "")
            {
                query = from u in context.UBIGEOs
                        where (u.Departamento.ToUpper().Contains(criterio) ||
                        u.Provincia.ToUpper().Contains(criterio) ||
                        u.Distrito.ToUpper().Contains(criterio)) ||
                        u.CodUbigeo.ToUpper().Contains(criterio)
                        select u;
            }

            return query.ToList();
        }

        public UBIGEO GetAllFRomUbigeoById(int id)
        {
            var query = from e in context.UBIGEOs
                        where e.Id.Equals(id)
                        select e;
            return query.SingleOrDefault();
        }

        public bool ExisteDuplicidad(string departamento, string provincia, string distrito, string ubigeo, int id)
        {
            var query = from u in context.UBIGEOs
                        where u.Departamento.ToUpper().CompareTo(departamento.ToUpper()) == 0
                        && u.Provincia.ToUpper().CompareTo(provincia.ToUpper()) == 0
                        && u.Distrito.ToUpper().CompareTo(distrito.ToUpper()) == 0
                        && u.CodUbigeo.ToUpper().CompareTo(ubigeo.ToUpper()) == 0
                        && u.Id != id
                        select u;
            return query.Any();

        }

        public void AddUbigeo(UBIGEO ubigeo)
        {
            context.UBIGEOs.Add(ubigeo);
            context.SaveChanges();
        }

        public void UpdateUbigeo(UBIGEO ubigeo)
        {
            context.Entry(ubigeo).State = System.Data.EntityState.Modified;
            context.SaveChanges();
        }

        public void DeleteUbigeo(int id)
        {
            var existe = context.UBIGEOs.Find(id);

            if (existe != null)
            {
                context.UBIGEOs.Remove(existe);
                context.SaveChanges();
            }
        }


        public UBIGEO getAllFromUbigeoByCodigo(string codigo)
        {
            var query = from c in context.UBIGEOs
                        where c.CodUbigeo.Contains(codigo)
                        select c;
            return query.SingleOrDefault();
        }
    }
}
